package com.herr.springboot.base.integration.extend;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 异常统一处理
 * @author herr05
 */
@RestControllerAdvice
public class ControllerAdvice {

	/**
	 * 自定义业务异常
	 * @param e
	 * @param response
	 * @return
	 */
	@ExceptionHandler(BizException.class)
	@ResponseStatus(HttpStatus.OK)
	public String handleBizException(BizException e, HttpServletResponse response)  {
		response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
		String apiResult=e.getMessage();
		return apiResult;
	}

	/**
	 * 404异常
	 * 为了捕获404异常，需要设置throw-exception-if-no-handler-found: true和add-mappings: false。
	 * 且在配置静态资源映射中（参考WebMvcConfig.java）避免使用/**路径，否则不会生效。
	 * @param e
	 * @param request
	 * @param response
	 * @return
	 */
	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public String handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request, HttpServletResponse response)  {
		response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
		String apiResult=e.getMessage();
		return apiResult;
	}

	@ExceptionHandler(Throwable.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public String handleException(Throwable e,HttpServletResponse response)  {
		response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
		String apiResult=e.getMessage();
		return apiResult;
	}
}